package cn.john.hrm.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;

// 标识为配置类
@Configuration
// 开启资源服务配置
@EnableResourceServer
// 开启注解方法授权
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class CourseResourceConfig extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        // 配置资源服务的id
        resources.resourceId("courseId");
        // 配置校验的token服务
        resources.tokenServices(tokenServer());
    }

    private ResourceServerTokenServices tokenServer() {
        RemoteTokenServices tokenServices = new RemoteTokenServices();
        tokenServices.setClientId("admin");
        tokenServices.setClientSecret("1");
        tokenServices.setCheckTokenEndpointUrl("http://localhost:3010/oauth/check_token");
        return tokenServices;

    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // 校验scope，对应认证服务的客户端详情配置的clientId
                .antMatchers("/**").access("#oauth2.hasScope('hrm')")
                // 关闭跨站
                .and().csrf().disable()
                // 把session设置为无状态，用了token不需要用session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}
